package com.dragon.logical.service.contract.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.DateNumUtils;
import com.dragon.logical.service.contract.IRejectedService;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * <p>
 * 退货表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-12-05
 */
@Service
public class RejectedServiceImpl extends ServiceImpl<RejectedMapper, Rejected> implements IRejectedService {

    @Autowired
    RejectedMapper rejectedMapper;
    @Autowired
    ProduceMapper produceMapper;
    @Autowired
    ProduceProductsMapper produceProductsMapper;
    @Autowired
    DeliverMapper deliverMapper;
    @Autowired
    RejectedProductMapper rejectedProductMapper;

    @Override
    public Page<Rejected> rejectedList(String name,Integer status,Integer page, Integer limit) {

        Page<Rejected> rejectedPage = new Page<>(page, limit);

        QueryWrapper<Rejected> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StrUtil.isNotBlank(name),"dc.name",name)
                .eq(status!=null,"dr.status",status)
                .eq("dr.deleted", 0)
                .orderByDesc("dr.create_time");

        Page<Rejected> rejectedPage1 = rejectedMapper.selectItemPage(rejectedPage,queryWrapper);

        return rejectedPage1;
    }


    @Override
    public Rejected selectDetailById(Integer id){
        Rejected rejected = rejectedMapper.selectDetailById(id);
        // 获取产品表详情
        if (rejected != null){
            List<RejectedProduct> rejectedProducts = rejectedProductMapper.selectProductList(id,rejected.getProduceId());
            rejected.setRejectedProducts(rejectedProducts);
            return rejected;
        } else {
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AddPageData rejectedOperate(Rejected rejected) {
        // 传 当前需要退货的生产产品表id，数量，用户id，部门id
        //自动生成编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String code = "TH_"+ sdf.format(DateUtil.date());
        String maxCode =  rejectedMapper.maxRoundInoutNumber(code);
        String newCode = null;
        if (StrUtil.isEmpty(maxCode)){
            newCode = code + "001";
        }
        else {
            String getMaxCode = maxCode.substring(11, 14);
            newCode = code + DateNumUtils.getNum(getMaxCode);
        }

        // 修改退货主表
        rejected.setRejectedCode(newCode);
        rejected.setCreateTime(DateUtil.date());
        rejectedMapper.insert(rejected);

        LambdaQueryWrapper<ProduceProducts> lambdaQueryWrapper = new LambdaQueryWrapper();
        //插入退货子表信息
        rejected.getRejectedProducts().forEach(e->{
            e.setRejectedId(rejected.getId());
            rejectedProductMapper.insert(e);
            //修改生产单每条子表退货数量数据
            lambdaQueryWrapper.eq(ProduceProducts::getProduceId,rejected.getProduceId()).eq(ProduceProducts::getQuotesProductId,e.getProductId());
            ProduceProducts produceProducts = produceProductsMapper.selectOne(lambdaQueryWrapper);
            if (e.getRecededNum() == null){
                e.setRecededNum(0);
            }
            Integer num = e.getRecededNum() + produceProducts.getRejectedNum();
            produceProducts.setRejectedNum(num);
            produceProductsMapper.updateById(produceProducts);
        });

        //生成表单审核单据
        AddPageData addPageData = new AddPageData();
        addPageData.setWorkflowJson(rejected.getWorkflowJsonList());
        addPageData.setTitle(rejected.getName());
        addPageData.setAdminId(rejected.getAdminId());
        addPageData.setStreamType(25);
        addPageData.setCorrelationId(rejected.getId());
        addPageData.setExempt(rejected.getExempt());
        return addPageData;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void rejectedUpdate(Rejected rejected) {
        Rejected rejected1 = rejectedMapper.selectById(rejected.getId());
        if (rejected1 == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        if (rejected.getStatus() == 1){
            throw new CustomException(ResultCode.REJECTED_IS_AUDIT);
        }

        //查询产品子表数据
        List<RejectedProduct> rejectedProducts = rejectedProductMapper.selectList(
                new LambdaQueryWrapper<RejectedProduct>().eq(RejectedProduct::getRejectedId,rejected1.getId())
        );

        //删除退货子表数据，并删除生产单中产品子表数量
        rejectedProducts.forEach(rejectedProduct -> {
            ProduceProducts produceProducts = produceProductsMapper.selectOne(
                    new LambdaQueryWrapper<ProduceProducts>().eq(ProduceProducts::getProduceId,rejected1.getProduceId())
                            .eq(ProduceProducts::getQuotesProductId,rejectedProduct.getProductId())
            );
            Integer num = produceProducts.getRejectedNum() - rejectedProduct.getRecededNum();
            produceProducts.setRejectedNum(num);
        });

        //生产单修改完成，则直接删除退货表子表数据
        rejectedProductMapper.delete(new LambdaQueryWrapper<RejectedProduct>().eq(RejectedProduct::getRejectedId,rejected1.getId()));

        LambdaQueryWrapper<ProduceProducts> lambdaQueryWrapper = new LambdaQueryWrapper();
        //插入退货子表信息
        rejected.getRejectedProducts().forEach(e->{
            e.setRejectedId(rejected.getId());
            rejectedProductMapper.insert(e);
            //修改生产单每条子表退货数量数据
            lambdaQueryWrapper.eq(ProduceProducts::getProduceId,rejected.getProduceId()).eq(ProduceProducts::getQuotesProductId,e.getProductId());
            ProduceProducts produceProducts = produceProductsMapper.selectOne(lambdaQueryWrapper);
            Integer num = produceProducts.getRejectedNum() + produceProducts.getNum();
            produceProducts.setRejectedNum(num);
            produceProductsMapper.updateById(produceProducts);
        });
    }

    @Override
    public void rejectedDelete(Integer id) {
        Rejected rejected = rejectedMapper.selectById(id);
        if (rejected.getStatus() == 1){
            throw new CustomException(ResultCode.REJECTED_IS_AUDIT);
        }
        rejected.setDeleted(1);
        rejectedMapper.updateById(rejected);

        //修改退货子表信息
        List<RejectedProduct> rejectedProducts = rejectedProductMapper.selectList(
                new LambdaQueryWrapper<RejectedProduct>().eq(RejectedProduct::getRejectedId,rejected.getId())
        );

        //删除生产单中产品子表数量
        rejectedProducts.forEach(rejectedProduct -> {
            ProduceProducts produceProducts = produceProductsMapper.selectOne(
                    new LambdaQueryWrapper<ProduceProducts>().eq(ProduceProducts::getProduceId,rejected.getProduceId())
                            .eq(ProduceProducts::getQuotesProductId,rejectedProduct.getProductId())
            );
            Integer num = produceProducts.getRejectedNum() - rejectedProduct.getRecededNum();
            produceProducts.setRejectedNum(num);
            produceProductsMapper.updateById(produceProducts);
        });
    }

    @Override
    public Page<Produce> isDeliverProduce(String search,Integer page,Integer limit) {
        Page<Produce> producePage = new Page<>(page,limit);
        QueryWrapper<Produce> wrapper = new QueryWrapper<>();
        wrapper.ne("M.deliver_status", 0).and(StrUtil.isNotBlank(search),
                i->i.like("M.contractCode", search)
                        .or().like("M.customerName",search)
                );
        Page<Produce> produces = produceMapper.selectNotDeliver(producePage,wrapper);
        if(produces.getTotal() > 0){
            produces.getRecords().forEach(produce -> {
                List<ProduceProducts> produceProductsList = produceProductsMapper.selectListByProduceId(produce.getId());
                produce.setProduceProducts(produceProductsList);
            });
        }
        return produces;
    }

    @Override
    public List<RejectedProduct> getRpList(Integer rejectedId){
        Rejected rejected = rejectedMapper.selectById(rejectedId);
        List<RejectedProduct> rejectedProducts = rejectedProductMapper.selectProductList(rejectedId,rejected.getProduceId());
        return  rejectedProducts;
    }
}
